<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="hover">
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <el-table border stripe :data="roleList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbuttom', i1 === 0 ? 'dbtop' : '', 'vcenter']"
            >
              <!--一级菜单-->
              <el-col :span="5">
                <el-tag type="success" closable  @close="removeRightsById(scope.row, item1.id)">{{ item1.authName }}</el-tag
                ><span class="el-icon el-icon-caret-right"></span>
              </el-col>
              <!--二级和三级菜单-->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!--二级权限渲染区域-->
                  <el-col :span="6">
                    <el-tag type="danger" closable  @close="removeRightsById(scope.row, item2.id)">{{ item2.authName }}</el-tag
                    ><span class="el-icon el-icon-caret-right"></span>
                  </el-col>
                  <!-- 三级权限渲染区域-->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                    &nbsp;
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--            <pre>{{scope.row}}</pre>-->
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180">
        </el-table-column>
        <!-- 操作按钮-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditRoleDialog(scope.row)">编辑</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope)">分配角色</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delRoleBtn(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!-- 分配权限弹窗-->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
    <!-- 弹出框主体-->
      <div>
        <el-tree
          ref="setRole"
          :data="rightsTree"
          :props="treeProps"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defKeys"
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoles" >确 定</el-button>
      </span>
    </el-dialog>
<!--    添加角色弹出框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleVisible"
      width="30%">
      <el-form ref="roleRef" :model="role" :rules="roleRoles" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色说明">
          <el-input type="textarea" v-model="role.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddRole">立即创建</el-button>
      </span>
    </el-dialog>
    <!--    修改角色弹出框-->
    <el-dialog
      title="添加角色"
      :visible.sync="editRoleVisible"
      width="30%">
      <el-form ref="editRoleRef" :model="editRole" :rules="roleRoles" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色说明">
          <el-input type="textarea" v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditRole">立即创建</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      roleList: [],
      // 控制分配权限对话框显示与隐藏
      SetRightDialogVisible: false,
      addRoleVisible: false,
      editRoleVisible: false,
      rightsTree: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      role: {
        roleName: '',
        roleDesc: ''
      },
      editRole: {},
      // 默认选中的节点默认值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
      roleRoles: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    // 获取所有用户
    getRolesList: async function() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      // console.log(res)
    },
    // 根据id删除权限
    async removeRightsById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.warn(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        role.children = res.data
        console.log(res.data)
        // console.log(res)
      }
    },
    // 展示分配权限的对话框
    async showSetRightDialog(scope) {
      this.roleId = scope.row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightsTree = res.data
      this.getLeafKeys(scope.row, this.defKeys)
      // console.log(this.defKeys)
      this.SetRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存 defkeys 的数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含children 属性说明为三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 保存权限
    async saveRoles() {
      const Keys = [
        ...this.$refs.setRole.getCheckedKeys(),
        ...this.$refs.setRole.getHalfCheckedKeys()
      ]
      const idStr = Keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) { return this.$message.error(res.meta.msg) }
      this.$message.success(res.meta.msg)
      this.SetRightDialogVisible = false
      // console.log(res)
    },
    // 监听权限分配对话框关闭事件
    setRightDialogClosed() {
      this.defKeys = []
      this.getRolesList()
    },
    // 显示添加角色
    addRoles() {
      this.addRoleVisible = true
      this.role.roleName = ''
      this.role.roleDesc = ''
    },
    // 保存创建角色
    saveAddRole: function() {
      this.$refs.roleRef.validate(async (valid) => {
        if (valid) {
          const { data: ref } = await this.$http.post('roles', { roleName: this.role.roleName, roleDesc: this.role.roleDesc })
          if (ref.meta.status !== 201) { return this.$message.error(ref.meta.msg) }
          this.$message.success(ref.meta.msg)
          this.addRoleDialogClosed()
          // console.log(ref)
          // alert('submict!')
        }
      })
    },
    // 关闭添加角色窗口
    addRoleDialogClosed() {
      this.getRolesList()
      this.addRoleVisible = false
    },
    delRoleBtn: function(scopeRow) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + scopeRow.id)
        if (res.meta.status !== 200) { return this.$message.error(res.meta.msg) }
        this.$message.success(res.meta.msg)
        this.getRolesList()
        // console.log(scopeRow)
      }).catch(() => {
        this.$message.info('你取消了删除')
      })
    },
    async showEditRoleDialog(scopeRow) {
      // 获取当前角色信息
      const { data: ref } = await this.$http.get('roles/' + scopeRow.id)
      if (ref.meta.status !== 200) { return this.$message.error(ref.meta.msg) }
      this.editRole = ref.data
      console.log(ref.data)
      this.editRoleVisible = true
    },
    saveEditRole: function() {
      this.$refs.editRoleRef.validate(async (valid) => {
        if (valid) {
          const { data: ref } = await this.$http.put('roles/' + this.editRole.roleId, { roleName: this.editRole.roleName, roleDesc: this.editRole.roleDesc })
          if (ref.meta.status !== 200) { return this.$message.error(ref.meta.msg) }
          this.$message.success(ref.meta.msg)
          this.getRolesList()
          this.editRoleVisible = false
          // console.log(ref)
        }
      })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 0 5px;
}
.block {
  margin-top: 15px;
}
.el-col {
  padding: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbuttom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
  .box-card{min-width: 960px}
</style>
